#coding:utf8
#
# Author: CMGS
# Created on 2010-8-25
#

import gevent.monkey
gevent.monkey.patch_all()
import utils.gtornado
utils.gtornado.patch_all()

import os
import sys
import getopt
import tornado.httpserver
import tornado.ioloop
import tornado.web

import init
from utils import autoreload
from appeditor import apieditor
from appjoin import apijoin
from appmsg import apimsg
from appcontrol import apicontrol
from appuser import apiuser
from appshare import apishare

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()
    
    def get(self):
        self.write("Hello World")

class EditorHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        sid = self.get_argument('sid')
        self.write(apieditor.getModify(hash, sid))

class ReFreshHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        sid = self.get_argument('sid')
        self.write(apiuser.keepOnline(hash, sid))

class ModifyHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        sid = self.get_argument('sid')
        msg = self.get_argument('msg')
        ret = apimsg.update(hash, sid, msg)
        if ret is not None:
            self.write(ret)
        else:
            self.write('None')

class JoinHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        token = self.get_argument('token', '')
        self.write(apijoin.newJoin(hash, token))

class CloseJoinHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        sid = self.get_argument('sid')
        self.write(apijoin.closeJoin(hash, sid))

class ShareHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        token = self.get_argument('token')
        fileId = self.get_argument('fileId')
        sharers = self.get_argument('sharers')
        writable = bool(int(self.get_argument('writable')))
        self.write(apishare.share(token, fileId, sharers, writable))

class ShowMsgArray(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        p = 0
        f = apicontrol.get(hash, p)
        o = []
        while f is not None:
            import json
            o.append(json.dumps(f))
            p += 1
            f = apicontrol.control.getMsg(hash, p)
        self.write('<br />'.join(o))

class SaveHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        sid = self.get_argument('sid')
        v = self.get_argument('v')
        self.write(apiuser.updateVector(hash, sid, v))

class KickHandler(tornado.web.RequestHandler):
    def post(self):
        self.get()

    def get(self):
        hash = self.get_argument('hash')
        sid = self.get_argument('sid')
        username = self.get_argument('username')
        self.write(apiuser.kickUser(hash, sid, username))

application = tornado.web.Application([
    (r'/', MainHandler),
    (r'/join', JoinHandler),
    (r'/editor', EditorHandler),
    (r'/save', SaveHandler),
    (r'/modify', ModifyHandler),
    (r'/logout', CloseJoinHandler),
    (r'/refresh', ReFreshHandler),
    (r'/kick', KickHandler),
    (r'/share', ShareHandler),
    (r'/show', ShowMsgArray),
    (r'/(crossdomain\.xml)', tornado.web.StaticFileHandler, {'path': os.path.join(os.path.dirname(__file__), '')}),
])

def run(port = 8080, ip = '127.0.0.1'):
    print 'run on %s:%d' % (ip, port)
    init.sysinit()
    http_server = tornado.httpserver.HTTPServer(application, ip, port)
    http_server.listen()
    tornado.ioloop.IOLoop.instance().start()

def main(port, ip, reload):
    if reload:
        autoreload.main(run, (port, ip))
    run(port, ip)

if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], "p:i:", ["reload"])
        port, ip, reload = 8080, '127.0.0.1', False
        for o, a in opts:
            port = int(a) if o == '-p' else port
            ip = a if o == '-i' else ip
            reload = True if o == '--reload' else reload
        main(port, ip, reload)
    except getopt.GetoptError:
        print 'python run.py -p [port] -i [blind ip] [--reload]'
